package com.jt.redis;

import com.sun.org.apache.xpath.internal.operations.Mult;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class SecondKillDemo1 {
    public static void main(String[] args) {
        Jedis jedis=new Jedis("192.168.126.129",6379);
        jedis.expire("ticket", 1);
        jedis.set("ticker", "1");
        jedis.set("money", "0");

        jedis.close();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                secondKillTicker();
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                secondKillTicker();
            }
        });
        t1.start();
        t2.start();
    }

    static void secondKillTicker() {
        Jedis jedis = new Jedis("192.168.126.129", 6379);
        String ticket = jedis.get("ticket");
        if (ticket!=null&&"".equals(ticket)&Integer.valueOf(ticket)==0)
            throw new RuntimeException("余额不足");
        jedis.watch("ticket","money");
        Transaction multi = jedis.multi();
        try {

            multi.decr("ticket");
            multi.incrBy("money", 100);
            multi.exec();
        }catch (Exception e){
            multi.discard();
        }finally {
            jedis.unwatch();
            jedis.close();
        }



    }


}
